package com.zxb.base.monitor.vo;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zxb.base.monitor.util.FormatUtil;
import com.zxb.base.monitor.util.LayoutUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Zxb
 */
@Data
@Builder
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class Disk {
    /**
     * 盘符
     */
    private List<Drive> devices;

    @Override
    public String toString() {
        return Optional.ofNullable(devices).orElse(ListUtil.empty()).stream().map(Drive::toString).collect(Collectors.joining(StrUtil.LF));
    }

    public JSONArray toJSON() {
        JSONArray ja = new JSONArray();
        for(Drive device:devices){
            JSONObject jo = new JSONObject();
            jo.put("name", device.getName());
            jo.put("totalSpace", FormatUtil.formatByteSize(device.getTotalSpace()));
            jo.put("freeSpace", FormatUtil.formatByteSize(device.getFreeSpace()));
            jo.put("usedSpace", FormatUtil.formatByteSize(device.getUsedSpace()));
            jo.put("driveSpace", NumberUtil.mul(device.getDriveUsage(), 100).setScale(2, RoundingMode.HALF_UP) + "%");
            ja.add(jo);
        }
        return ja;
    }

    /**
     * 盘符
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Drive {

        /**
         * 盘符名称
         */
        private String name;

        /**
         * 总大小
         */
        private long totalSpace;

        /**
         * 空闲大小
         */
        private long freeSpace;

        /**
         * 已用大小
         */
        private long usedSpace;

        /**
         * 盘符使用率
         */
        private BigDecimal driveUsage;

        @Override
        public String toString() {
            return LayoutUtil.Table.of(name,
                    LayoutUtil.Row.of("Total Space", FormatUtil.formatByteSize(totalSpace)),
                    LayoutUtil.Row.of("Free Space", FormatUtil.formatByteSize(freeSpace)),
                    LayoutUtil.Row.of("Used Space", FormatUtil.formatByteSize(usedSpace)),
                    LayoutUtil.Row.of("Drive Space", NumberUtil.mul(driveUsage, 100).setScale(2, RoundingMode.HALF_UP) + "%")
            ).toString();
        }
    }
}
